package com.example.demo.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.mapper.CourseMapper;
import com.example.demo.entity.Course;
import com.example.demo.entity.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class UpdateCourseController {
    @Autowired
    private CourseMapper cm;
    @RequestMapping("/updatecourse")
    public void updateCourse(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int courseid=Integer.valueOf(request.getParameter("courseid"));
        int id=Integer.valueOf(request.getParameter("id"));
        String teachername=request.getParameter("teachername");
        String coursename=request.getParameter("coursename");
        Float grdit=Float.valueOf(request.getParameter("gredit"));
        String term=request.getParameter("term");
        String begintime=request.getParameter("begintime");
        String endtime=request.getParameter("endtime");
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        List<Course> list =new ArrayList<Course>();
        list=cm.findAlllCourse();
        boolean isIdExist=list.stream().anyMatch(course -> course.getId()==id);
        boolean isTeacherNameExist=list.stream().anyMatch(course -> course.getTeachername().equals(teachername));
        boolean isCourseNameExist=list.stream().anyMatch(course -> course.getCoursename().equals(coursename));
        String regex = "^20\\d{2}-20\\d{2}-[1,2]$";
        boolean isValidTerm = term.matches(regex);
        Date begt;
        Date endt;
        if(isIdExist&&isTeacherNameExist&&isCourseNameExist&&isValidTerm) {
            try {
                 begt = df.parse(begintime);
                 endt = df.parse(endtime);
            } catch (ParseException e) {
                response.getWriter().write(JSONObject.toJSONString(Message.failure("Input date is illegal.")));
                return;
            }
            int n = cm.updateCou(teachername,coursename,grdit,term,begt,courseid,id,endt);
            if (n > 0) {
                response.getWriter().write(JSONObject.toJSONString(Message.success("Success update")));
            } else response.getWriter().write(JSONObject.toJSONString(Message.failure("Failure update")));
        }else response.getWriter().write(JSONObject.toJSONString(Message.failure("The data you input does not exist or is illegal.")));
    }
}
